package es.unex.meigas.extFillData;

import java.awt.Cursor;
import java.util.ArrayList;

import es.unex.meigas.core.DasocraticElement;
import es.unex.meigas.core.Tree;
import es.unex.meigas.extBase.BaseWizardPanel;
import es.unex.meigas.extBase.MainWizardWindow;
import es.unex.meigas.gui.MeigasPanel;
import es.unex.sextante.libMath.regression.LeastSquaresFit;

public class FillDataExtensionPanel extends MainWizardWindow{


    public FillDataExtensionPanel(MeigasPanel panel) {

    	super(panel);

    	setName("Rellenado de datos");

	}

	protected void finish() {


		int iTree, iVariable;
		int iTreesCount;
		double dX, dY;
		Tree tree;
		XYVariables variable;
		LeastSquaresFit lsf = new LeastSquaresFit();
		ArrayList trees = m_MeigasPanel.getActiveElement().getTrees();
		ArrayList variables = ((FillDataPanel)m_Panels[0]).getVariables();

		for (iVariable = 0; iVariable < variables.size(); iVariable++){
			this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			variable = (XYVariables)variables.get(iVariable);
			iTreesCount = 0;
			for (iTree = 0; iTree < trees.size(); iTree++){
				tree = (Tree) trees.get(iTree);
				dY = getValue(variable.y, tree);
				if (dY != DasocraticElement.NO_DATA){
					dX = getValue(variable.x, tree);
					if (dX != DasocraticElement.NO_DATA){
						lsf.addValue(dX, dY);
						iTreesCount++;
					}
				}
			}
			if (iTreesCount < 2){
				continue;
			}

			lsf.calculate(1);

			this.setCursor(Cursor.getDefaultCursor());

			FittingDataPanel dialog = new FittingDataPanel(lsf, trees, variable);
			dialog.setVisible(true);

		}

	}

	private double getValue(int y, Tree tree){

		double dValue;

		switch (y){
		case FillDataPanel.DBH:
			dValue = tree.getDBH().getValue();
			break;
		case FillDataPanel.HEIGHT:
			dValue = tree.getHeight().getValue();
			break;
		case FillDataPanel.LOG_HEIGHT:
			dValue = tree.getLogHeight().getValue();
			break;
		case FillDataPanel.VOLUME_WITH_BARK:
			dValue = tree.getVolumeWithBark().getValue();
			break;
		case FillDataPanel.VOLUME_WITHOUT_BARK:
			dValue = tree.getVolumeWithoutBark().getValue();
			break;
		case FillDataPanel.BARK:
			dValue = tree.getBark().getValue();
			break;
		case FillDataPanel.CROWN_DIAMETER:
			dValue = tree.getCrownDiameter().getValue();
			break;
		default:
			return DasocraticElement.NO_DATA;
		}

		return dValue;

	}

	protected void setPanels() {

		m_Panels = new BaseWizardPanel[1];
		m_Panels[0] = new FillDataPanel(this);

	}
}
